<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\translation;

use app\common\model\ContentTranslation;
use app\common\model\TranslationJob;
use app\common\model\TranslationConfig;
use app\common\model\Language;

/**
 * 内容翻译服务类
 */
class ContentTranslationService
{
    private $translateApiService;

    public function __construct()
    {
        $this->translateApiService = new TranslateApiService();
    }

    /**
     * 为指定内容创建翻译任务
     */
    public function createTranslationJob($tableName, $recordId, $fieldName, $targetLanguages = null)
    {
        // 获取翻译配置
        $config = TranslationConfig::getFieldConfig($tableName, $fieldName);
        if (!$config || !$config->is_enabled) {
            return false;
        }

        // 确定目标语言
        if (!$targetLanguages) {
            $targetLanguages = $config->target_languages ?: Language::getEnabledLanguages()->column('code');
        }

        // 创建翻译任务
        $job = TranslationJob::createJob($tableName, $recordId, $fieldName, $targetLanguages);

        // 如果启用自动翻译，立即处理
        if ($config->auto_translate) {
            $this->processTranslationJob($job->id);
        }

        return $job;
    }

    /**
     * 处理翻译任务
     */
    public function processTranslationJob($jobId)
    {
        $job = TranslationJob::find($jobId);
        if (!$job || $job->status != TranslationJob::STATUS_PENDING) {
            return false;
        }

        // 标记任务为处理中
        $job->markAsProcessing();

        try {
            // 获取原始内容
            $originalContent = $this->getOriginalContent($job->table_name, $job->record_id, $job->field_name);
            if (!$originalContent) {
                throw new \Exception('原始内容不存在');
            }

            $successCount = 0;

            // 为每种目标语言创建翻译
            foreach ($job->target_languages as $languageCode) {
                if ($languageCode === 'zh_CN') {
                    // 中文是原始语言，直接保存
                    ContentTranslation::saveTranslation(
                        $job->table_name,
                        $job->record_id,
                        $job->field_name,
                        $languageCode,
                        $originalContent,
                        $originalContent,
                        'original'
                    );
                    $successCount++;
                    continue;
                }

                try {
                    // 调用翻译API
                    $translatedContent = $this->translateApiService->translate($originalContent, $languageCode, 'zh_CN');

                    // 保存翻译结果
                    ContentTranslation::saveTranslation(
                        $job->table_name,
                        $job->record_id,
                        $job->field_name,
                        $languageCode,
                        $originalContent,
                        $translatedContent,
                        $this->translateApiService->getLastUsedProvider()
                    );

                    $successCount++;
                } catch (\Exception $e) {
                    // 记录翻译失败
                    ContentTranslation::saveTranslation(
                        $job->table_name,
                        $job->record_id,
                        $job->field_name,
                        $languageCode,
                        $originalContent,
                        '',
                        null,
                        2,
                        $e->getMessage()
                    );
                }
            }

            // 更新任务状态
            if ($successCount > 0) {
                $job->markAsCompleted();
            } else {
                $job->markAsFailed('所有语言翻译失败');
            }

            return true;

        } catch (\Exception $e) {
            $job->markAsFailed($e->getMessage());
            return false;
        }
    }

    /**
     * 获取原始内容
     */
    private function getOriginalContent($tableName, $recordId, $fieldName)
    {
        $model = $this->getModelByTableName($tableName);
        if (!$model) {
            return null;
        }

        $record = $model::find($recordId);
        return $record ? $record->{$fieldName} : null;
    }

    /**
     * 获取翻译内容
     */
    public function getTranslatedContent($tableName, $recordId, $fieldName, $languageCode = 'zh_CN')
    {
        // 如果是默认语言，直接返回原始内容
        if ($languageCode === 'zh_CN') {
            return $this->getOriginalContent($tableName, $recordId, $fieldName);
        }

        $translation = ContentTranslation::getTranslation($tableName, $recordId, $fieldName, $languageCode);
        if ($translation) {
            return $translation->translated_content;
        }

        // 如果没有翻译，返回原始内容
        return $this->getOriginalContent($tableName, $recordId, $fieldName);
    }

    /**
     * 批量获取翻译内容
     */
    public function batchGetTranslatedContent($items, $languageCode = 'zh_CN')
    {
        if ($languageCode === 'zh_CN' || empty($items)) {
            return $items; // 默认语言直接返回
        }

        // 按表名分组处理
        $groupedItems = $this->groupItemsByTable($items);

        foreach ($groupedItems as $tableName => $tableItems) {
            $this->processTableTranslations($tableName, $tableItems, $languageCode, $items);
        }

        return $items;
    }

    /**
     * 按表名分组项目
     */
    private function groupItemsByTable($items)
    {
        $grouped = [];
        foreach ($items as $index => $item) {
            if (!isset($item['_table_name']) || !isset($item['_record_id'])) {
                continue;
            }
            $grouped[$item['_table_name']][] = [
                'index'     => $index,
                'record_id' => $item['_record_id'],
                'item'      => $item
            ];
        }
        return $grouped;
    }

    /**
     * 处理表的翻译
     */
    private function processTableTranslations($tableName, $tableItems, $languageCode, &$items)
    {
        $recordIds = array_column($tableItems, 'record_id');
        $configs   = TranslationConfig::getTableConfig($tableName);

        foreach ($configs as $config) {
            $translations   = ContentTranslation::batchGetTranslations($tableName, $recordIds, $languageCode);
            $translationMap = [];

            foreach ($translations as $translation) {
                if ($translation['field_name'] === $config->field_name) {
                    $translationMap[$translation['record_id']] = $translation['translated_content'];
                }
            }

            foreach ($tableItems as $tableItem) {
                $recordId = $tableItem['record_id'];
                $index    = $tableItem['index'];

                if (isset($translationMap[$recordId])) {
                    $items[$index][$config->field_name] = $translationMap[$recordId];
                }
            }
        }
    }

    /**
     * 根据表名获取模型类
     */
    private function getModelByTableName($tableName)
    {
        $modelMap = [
            'goods'          => \app\common\model\Goods::class,
            'goods_category' => \app\common\model\GoodsCategory::class,
            'articles'       => \app\common\model\Article::class,
            'site_config'    => \app\common\model\SystemConfig::class,
            // 可以根据需要添加更多表名到模型的映射
        ];

        return $modelMap[$tableName] ?? null;
    }

    /**
     * 批量处理翻译任务
     */
    public function batchProcessJobs($limit = 10)
    {
        $jobs      = TranslationJob::getPendingJobs($limit);
        $processed = 0;

        foreach ($jobs as $job) {
            try {
                $this->processTranslationJob($job->id);
                $processed++;
            } catch (\Exception $e) {
                // 记录错误但继续处理其他任务
                error_log("Translation job {$job->id} failed: " . $e->getMessage());
            }
        }

        return $processed;
    }

    /**
     * 获取翻译统计信息
     */
    public function getTranslationStats()
    {
        return [
            'translations' => ContentTranslation::getTranslationStats(),
            'jobs'         => TranslationJob::getJobStats(),
            'configs'      => TranslationConfig::getConfigStats(),
        ];
    }
}
